﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class EvtVJS : System.EventArgs
{
	// quaternion in world axis;
	private Quaternion quSqr;
	public Camp campInfo;

	public Quaternion ToSqrQuat
	{
		get {return quSqr;}
	}

	public EvtVJS (Quaternion qu)
	{
		float angle;
		Vector3 axis;
		
		qu.ToAngleAxis(out angle, out axis);

		quSqr = Quaternion.AngleAxis(-angle,Vector3.up); 
	}
}

public class VirtualJoystick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler{
	
	public PlayerForces playerForce;

	public GameObject joyStick;
	public GameObject sitckCenter;

	private Quaternion joystickQuate;

	public System.EventHandler<EvtVJS> evtRotation;

	// Use this for initialization
	void Start () {
		playerForce.evtUIHandlerMsg += OnUIMessage;
	}
	
	// Update is called once per frame
	void Update () {
		sitckCenter.transform.rotation = joystickQuate;
	}

	public void OnBeginDrag (PointerEventData eventData)
	{
		if (false == eventData.pointerDrag.Equals(joyStick))
			Debug.LogError("Drag event source error!");
	}

	public void OnDrag (PointerEventData eventData)
	{
		if (false == eventData.pointerDrag.Equals(joyStick))
			Debug.LogError("Drag event source error!");

		joystickQuate = Quaternion.FromToRotation (Vector3.up, eventData.position - eventData.pressPosition);

		if (null != evtRotation)
		{
			EvtVJS evt = new EvtVJS (joystickQuate);
			evt.campInfo = playerForce.CurSelSquare.GetComponent<Camp>();
			evtRotation (this, evt);
		}
	}

	public void OnEndDrag (PointerEventData eventData)
	{
		if (false == eventData.pointerDrag.Equals(joyStick))
			Debug.LogError("Drag event source error!");
	}

	void OnUIMessage(object sender, UIPlayerMessage msg)
	{
		if (msg.playerAct == EUIAction.eSelSquare)
		{
			Quaternion rotate = playerForce.CurSelSquare.GetComponent<SquareMove>().DstOrientation;

			float angle;
			Vector3 axis;

			rotate.ToAngleAxis(out angle, out axis);

			joystickQuate = Quaternion.AngleAxis(angle, Vector3.forward);
		}
	}
}

